import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.*;
import java.util.Scanner;
import java.util.regex.Pattern;

import static java.util.UUID.randomUUID;

public class TieGoods {

    private static final Logger log = LoggerFactory.getLogger(TieGoods.class);

    private static FileOutputStream fos = null;
    private static Scanner in = new Scanner(System.in);
    private static String type;
    private static Pattern pattern;

    public static void main(String[] args) {
        System.out.println("贴宝，一款免除头痛的实验课代码粘贴器");
        System.out.print("Give me an ABSOLUTE PATH（文件夹绝对路径）: ");
        String path = in.next();
        if ("".equals(path.trim())){
            log.error("Empty input!");
            return;
        }
        // 获得当前文件
        File curr = new File(path);
        if (!curr.exists()){
            log.error(curr.getName() + " not exist!");
            return;
        }
        // 获取过滤字符
        System.out.print("输入文件通配符， 例如：*.java: ");
        while (true){
            type = in.next();
            if ("".equals(type.trim()) || "\n".equals(type.trim())){
                System.out.print("请正确输入文件名称：");
                continue;
            }
            break;
        }

        // 解析通配符生成regex
        type = type.replace('.', '#');
        type = type.replaceAll("#", "\\\\.");
        type = type.replace('*', '#');
        type = type.replaceAll("#", ".*");
        type = type.replace('?', '#');
        type = type.replaceAll("#", ".?");
        type = "^" + type + "$";

        System.out.println("[INFO]: 使用正则表达式：" + type);
        pattern = Pattern.compile(type);

        // 创建输出文件并且绑定输出流
        String target = path+File.separator+"TieGoods_"+randomUUID()+"_generated";
        try {
            fos = new FileOutputStream(new File(target));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        TieGoods tieGoods = new TieGoods();
        tieGoods.read(curr);

        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done! file generated at \"" + target + "\"");
    }

    /**
     * 读取文件
     * @param curr 文件(或目录)
     */
    private void read(File curr){
        if (curr.isDirectory()){
            File[] files = curr.listFiles();
            assert files != null;
            for (File file : files) {
                // 迭代处理文件夹
                if (file.isDirectory()) {
                    log.debug("encountered with dir: " + file.getPath());
                    read(file);
                } else {
                    String name = file.getName();
                    if (pattern.matcher(name).matches()) {
                        // 如果是要求的文件
                        if (write2File(file)){
                            log.debug("read file " + file.getName() + " success");
                        }
                    }
                }
            }
        }
    }

    /**
     * 向目标文件写入当前文件内容
     * @param file  当前文件
     */
    private boolean write2File(File file){
        boolean flag = false;
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = -1;
            // 写入文件名注释
            String str = "\n\n" +
                    "/*\n" +
                    "* " + file.getCanonicalPath() +
                    "\n*/\n\n";
            fos.write(str.getBytes());
            while((len = fis.read(bytes))!=-1){
                fos.write(bytes, 0, len);
            }
            fis.close();
            fos.flush();
            flag = true;
        }catch (IOException e){
            // 写入失败
            log.error("failed to write " + file.getName());
        }
        return flag;
    }
}
